<template>
  <el-container>
      <el-main>
        <el-form ref="payable" :model="form" :rules="rules" label-width="80px">
          <div style="display: flex">
            <el-form-item label="装车仓库">
              <queryShop  @queryShopClick="queryShopClick"></queryShop>
            </el-form-item>
            <el-form-item label="送货人员"  prop="shippingEmployeeId">
              <el-select  :disabled="shippingEmployeedisbale" v-model="form.shippingEmployeeId" clearable placeholder="请选择送货员" @change="changeDelivery"
                         filterable @focus="getEmployeeList('')" :filter-method="queryEmployee" style="width: 100%">
                <el-option v-for="item in employee" :key="item.id" :label="item.name"
                        :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item label="装车日期">
              <el-date-picker
                style="width: 201px"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="备注留言" prop="memo" >
              <el-input v-model="form.memo" style="width: 480px"/>
            </el-form-item>

          </div>

          <div class="product_header_name" style="">
            <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">送货明细</span>
          </div>
          <el-table
            ref="shippingTable"
            :data="shippingList"
            :height="'52vh'"
            :summary-method="getSummaries"
            show-summary
            border
            stripe
            @select="handleSelectionChange"
            @select-all="handleSelectionAllChange"
            @selection-change="selectionChangeFn"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column label="订单日期" align="center" width="160">
              <template slot-scope="scope">
                <span>{{ scope.row.orderDate | datetimeFormatter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="送货单号" align="center" prop="sn" width="170" />

            <el-table-column label="客户信息" align="center"  >
               <template slot-scope="scope">
                  <div style="display: flex;flex-direction: column;justify-content: center" class="shop_Height">
                  <span class="table_ContentTitle">{{scope.row.consignee}} {{scope.row.phone}}</span>
                  <el-tooltip class="item" effect="dark" :content="scope.row.address" placement="top">
                    <span style="margin-top: 5px" class="table_ContentTitle">{{scope.row.address}}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="配送方式" align="center"  width="100" >
                <template slot-scope="scope">
                <span>{{ scope.row.shippingMethod|watchShippingMethod }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发货状态" align="center" width="100" >
              <template slot-scope="scope">
                <span>{{ scope.row.statusDescr }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品总数" width="100" align="center" prop="subQuantity">
              <template slot-scope="scope">
                <span>{{scope.row.subQuantity}}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品金额" align="center" prop="subPrice" width="120" />
            <el-table-column label="店铺优惠" align="center" prop="discount" width="120" >
              <template slot-scope="scope">
                <span>{{ scope.row.discount | watchDiscount}}</span>
              </template>
            </el-table-column>
            <el-table-column label="实付金额" align="center" prop="amountPaid" width="120" />
          </el-col>
          </el-table>

            <div style="display: flex;justify-content: space-between;">
                <!--<el-input v-model="unpayAmount" readonly />-->
              <div style="margin-top: 30px;">
               <!--  <span style="font-size: 16px;color: red;">对账金额：{{unpayAmount}}</span> -->
              </div>
              <!--<el-footer class="el-footerBox" style="margin-top: 10px;">-->
              <div style="margin-top: 30px;">

                <el-button v-permission="['picking.add']"  :loading="saveClicked" @click="saveClick" :disabled="selectionChange.length===0">保存</el-button>
                <el-button v-permission="['picking.audit']" type="primary" :loading="saveAndConfirmClicked" @click="saveAndConfirmClick" :disabled="selectionChange.length===0">保存并出库</el-button>
              </div>
              <!--</el-footer>-->
              <!--<el-button type="primary" style="margin-top: 20px" v-permission="['purchasein.in']" :loading="clicked" @click="saveInstockClick('purchaseForm')">保存并入库</el-button>-->
              <!--<el-button type="success" style="margin-top: 20px" v-permission="['purchase.audit']" :loading="clicked" @click="saveConfirmClick('purchaseForm')">保存并确认</el-button>-->
              <!--<el-button  style="margin-top: 20px" :loading="clicked" @click="saveClick('purchaseForm')">保存至草稿</el-button>-->
            </div>
          </div>
        </el-form>

      </el-main>

  </el-container>
</template>
<script>
  import { list as emoloyeeList } from '@/api/sysEmployee'
  import {EventBus} from '@/api/eventBus'
  import supplierTable from '../../components/SupplierTable/supplierList'
  import loadMore from '@/utils/loadMore.js'
  import { list as shippingList } from '@/api/shipping'
  import { save,saveAndConfirm } from '@/api/picking'
  import Pagination from '@/components/Pagination'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import queryShop from '@/components/Query/queryShop'
  import utils from '../../utils/utils.js'
  import ElRow from "element-ui/packages/row/src/row";
  export default {
    name: 'picking-add',
    directives: { loadMore, permission ,elDragDialog},
    components: {
      ElRow,
      Pagination ,queryShop},
    filters: {
      watchShippingMethod(val){
        if (val == 0) {
          return '普通快递'
        } else if (val == 1) {
          return '到店提货'
        } else if (val == 2) {
          return '同城快送'
        }
      },
      status(val) {
        if (val == 0) {
          return '未确认'
        } else if (val == 1) {
          return '已派单'
        } else if (val == 2) {
          return '已发货'
        } else if (val == 3) {
          return '已送达'
        } else if (val == 4) {
          return '已完成'
        } else if (val == 5) {
          return '已关闭'
        }
      },
      watchDiscount (val) {
        if (val === undefined) {
          return 0
        } else {
          return val
        }
      },
    },
    data() {
      return {
        shippingEmployeedisbale:true,
        employee: [],
        queryType: true,
        total: 0,
        productQty: 0,
        times:'',
        pageNum: 1,
        pageSize: 20,
        form: {
          shippingEmployeeId: '',
          type: 1,
          memo: '',
          orderDate: '',
          shippingIds: [],
          shopId:"",
        },
        shippingList: [],
        selectionChange: [],
        itemList: [],
        saveClicked: false,
        saveAndConfirmClicked:false,
        curHeight: null,
        rules: {
          employeeName:[
            {required: true, message: '请选择送货人员', trigger: 'blur'},
          ],
          orderDate: [
            {required: true, message: '业务日期不能为空', trigger: 'blur'},
          ],
        },
        pickerOptions: {// 时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created() {

    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      queryShopClick(data){
        console.log(data);
        this.form.shopId=data.shopId
        this.getEmployeeList()
        this.shippingEmployeedisbale=false
      },
      loadShipping() {//debugger
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', 1000)
        if (this.form.shippingEmployeeId != '' && this.form.shippingEmployeeId != null) {
          params.append('shippingEmployeeId', this.form.shippingEmployeeId)
        }
        params.append('shippingStatus', 2)  //已派单
        params.append('shopId',this.form.shopId)  //已派单
        shippingList(params).then(res => {
          this.shippingList = res.data.data;
        }).catch(err => { console.log(err) })

      },
      selectionChangeFn(data) {
        console.log(data);
        this.selectionChange = data
      },
      handleSelectionChange(data) {
        this.selectionChange = data;
        this.productQty = 0;
        this.selectionChange.forEach(item1 => {
          this.productQty = this.productQty + (Number(item1.subQuantity));

          // if (index !== -1) {
          //   this.shippingList[index].submitAmount = this.shippingList[index].restAmount
          // }
        })
      },
      handleSelectionAllChange(data) {
        // debugger
        this.selectionChange = data;
    /*    this.unpayAmount = 0;
        this.selectionChange.forEach(item1 => {
          this.unpayAmount = this.unpayAmount + (Number(item1.amount) - Number(item1.amountPaid));
        });
        this.unpayAmount = this.unpayAmount.toFixed(2);
        this.shippingList.forEach(item => {
          if (item.submitAmount !== '' || item.submitAmount !== '0.00') {
            item.submitAmount = item.restAmount
          }
        })*/
      },
      saveClick() {
        var _this = this;
        if (this.selectionChange.length === 0) {
          this.$message({ message: '请选择数据', type: 'warning' })
        } else {
          this.$confirm('是否生成装车单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveClicked = true;

            this.form.shippingIds = [];
            this.selectionChange.forEach(item => {
              this.form.shippingIds.push(item.id);
            })
//.debugger

            save(this.form).then(res => {
              _this.saveClicked = false;
              EventBus.$emit('picking-add', res.data);
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/picking/list'
                })
              })// 关闭当前tab回到列表
            }).catch(() => { this.saveClicked = false })
          });

        }
      },
      saveAndConfirmClick() {
        var _this = this;
        if (this.selectionChange.length === 0) {
          this.$message({ message: '请选择数据', type: 'warning' })
        } else {
          this.$confirm('是否生成装车单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveAndConfirmClicked = true;

            this.form.shippingIds = [];
            this.selectionChange.forEach(item => {
              this.form.shippingIds.push(item.id);
            })
            saveAndConfirm(this.form).then(res => {
              _this.saveAndConfirmClicked = false;
              EventBus.$emit('picking-add', res.data);
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/picking/list'
                })
              })// 关闭当前tab回到列表
            }).catch(() => { this.saveAndConfirmClicked = false })
          });

        }
      },
      getSummaries(param) {
        this.$nextTick(() => {
          this.$refs.shippingTable.doLayout()
        })
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (index === 2){
              return;
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                return prev
              }
            }, 0)
            if(index==6){
              sums[index] += ''
            }else{
              sums[index] += ' 元'
            }
          }
        })

        return sums
      },

      beforeMount() {
        window.onresize = () => {
          return (() => {
            const h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              this.curHeight = h - 266// 减去页面上固定高度height
            } else {
              this.curHeight = h - 220// 减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        const h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        const h = document.documentElement.clientHeight || document.body.clientHeight
        if (this.queryType === false) {
          this.curHeight = h - 266// 减去页面上固定高度height
        } else {
          this.curHeight = h - 220// 减去页面上固定高度height
        }
      },
      changeDelivery(val){
        this.form.shippingEmployeeId = val;
        this.loadShipping();
      },
      queryEmployee(query) {
        this.getEmployeeList(query)
      },
      getEmployeeList(query) {
        let param = new URLSearchParams()
        param.append('name', query)
        param.append('shopId', this.form.shopId)
        emoloyeeList(param).then(res => {
          console.log(res)
          console.log('送货员')
          this.employee = res.data.data
        })
      },
    }
  }
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
          padding: 10px;
          /* height: 100% !important; */
          padding-bottom: 0;
        }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_body{
    padding-top: 10px;
    padding-bottom: 10px;
    margin-top: 5px;
  }
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 20px;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
